import { onMounted, reactive, ref, unref, watch } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { downloadExcel } from '@/utils/file'

export function useTableCRUD ({
    api,
    searchData,
    listName = 'pageList',
    deleteName = 'deleteData',
    batchDeleteName = 'batchDelete',
    excelExportName = 'excelExport',
    deleteKey = 'kid',
    deleteId = 'kid',
    deleteMessage = '确定要删除该记录吗?',
    batchDeleteMessage = '确定要删除当前勾选的记录吗?',
    getDataOnMounted = true,
    hasList = true,
    enablePaginationData = true,
    pureBatchList = false
}) {
    const BaseTableRef = ref(null)
    const loading = ref(false)
    const paginationData = reactive({
        pageNum: 1,
        pageSize: 20,
        total: 0
    })
    const tableData = ref([])

    const getDataList = async () => {
        const { total, ...pageArgs } = paginationData
        const params = {
            ...(enablePaginationData ? pageArgs : {}),
            ...unref(searchData)
        }

        try {
            loading.value = true
            const res = await api[listName](params)
            if (hasList) {
                tableData.value = res.list || []
            } else {
                tableData.value = res || []
            }
            const { pageNum, pageSize, total } = res
            enablePaginationData && Object.assign(paginationData, {
                pageNum,
                pageSize,
                total
            })
        } catch (err) {
            ElMessage({
                type: 'error',
                message: err?.data?.msg || err?.message || 'Error',
                grouping: true
            })
        } finally {
            loading.value = false
        }
    }

    const flushData = async () => {
        paginationData.pageNum = 1
        await getDataList()
    }

    const handleDelete = async row => {
        try {
            await ElMessageBox.confirm(deleteMessage, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
            const params = {}
            params[deleteKey] = row[deleteId]
            await api[deleteName](params)
            ElMessage.success(`删除成功`)
            getDataList()
        } catch (err) {
            err !== `cancel` && ElMessage({
                type: 'error',
                message: err?.data?.msg || err?.message || 'Error',
                grouping: true
            })
        }
    }

    const handleBatchDelete = async () => {
        const batchList = unref(BaseTableRef)
            .tableRef.getSelectionRows()
            .map(row => ({ [deleteId]: row[deleteId] }))
        if (!batchList.length) {
            ElMessage.warning(`当前没有勾选记录`)
            return
        }
        try {
            await ElMessageBox.confirm(batchDeleteMessage, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
            if (pureBatchList) {
                await api[batchDeleteName](batchList.map(item => item.kid))
            } else {
                await api[batchDeleteName]({ batchList })
            }
            ElMessage.success(`删除成功`)
            getDataList()
        } catch (err) {
            err !== `cancel` && ElMessage({
                type: 'error',
                message: err?.data?.msg || err?.message || 'Error',
                grouping: true
            })
        }
    }

    const excelExport = async () => {
        downloadExcel({
            api: api[excelExportName],
            data: unref(searchData)
        })
    }

    onMounted(() => {
        if (getDataOnMounted) {
            getDataList()
        }
    })

    const resetTableData = () => {
        tableData.value = []
    }

    return {
        loading,
        paginationData,
        tableData,
        BaseTableRef,
        getDataList,
        flushData,
        handleDelete,
        handleBatchDelete,
        excelExport,
        resetTableData
    }
}

export default useTableCRUD